<script setup>
import { User, Lock, ChatLineRound } from "@element-plus/icons-vue";
import { ref, onUnmounted } from "vue";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router"; // 关于跳转路由
import { getCaptcha } from "@/api/captcha.js"; // 导入 getCaptcha 方法

// 控制注册与登录表单的显示，默认显示注册
const isRegister = ref(false); // 默认显示注册
const router = useRouter(); // 路由器
const registerData = ref({
  username: "",
  password: "",
  repassword: "",
  captcha: "",
  key: "",
  userType: "student" // 新增用户类型，默认学生
});

const loginData = ref({
  username: "admin",
  password: "12345",
  captcha: "",
  key: "",
});

// 密码校验
const checkPassword = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请再次确认密码"));
  } else if (value != registerData.value.password) {
    callback(new Error("两次输入的密码不一致"));
  } else {
    callback();
  }
};

// 定义表单校验规则
const regrules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 5, max: 16, message: "用户名长度要在5到16", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 5, max: 16, message: "密码长度要在5到16", trigger: "blur" },
  ],
  repassword: [
    {
      // 自定义校验规则
      validator: checkPassword,
      trigger: "blur",
    },
  ],
  captcha: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    { min: 4, max: 4, message: "验证码长度为4", trigger: "blur" },
  ],
  userType: [
    { required: true, message: "请选择用户类型", trigger: "change" }
  ]
};

const logrules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 5, max: 16, message: "用户名长度要在5到16", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 5, max: 16, message: "密码长度要在5到16", trigger: "blur" },
  ],
  captcha: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    { min: 4, max: 4, message: "验证码长度为4", trigger: "blur" },
  ],
  userType: [
    { required: true, message: "请选择用户类型", trigger: "change" }
  ]
};

// 注册
import { userRegisterService, userLoginService } from "@/api/user.js";
const register = async () => {
  registerData.value.key = keyy.value;
  try {
    let result = await userRegisterService(registerData.value);

    if (result.msg === "操作成功") {
      // 注册成功处理
      ElMessage.success(result.msg ? result.msg : "注册成功");
      // 可以选择跳转到登录页面或其他操作
      isRegister.value = false; // 切换到登录表单
      fetchCaptcha(); // 刷新验证码
    } else {
      // 注册失败处理
      fetchCaptcha(); // 刷新验证码
      ElMessage.error(`注册失败: ${result.msg || "未知错误"}`);
    }
  } catch (error) {
    // 捕获网络或其他异常
    console.error('注册请求失败:', error);
    fetchCaptcha(); // 刷新验证码
    ElMessage.error("注册请求失败，请稍后再试");
  }
};
import { useTokenStore } from "@/stores/token.js";
const tokenStore = useTokenStore();

// 验证码 URL
const captchaUrl = ref('');
// 前端生成key
const keyy = ref('');

// 获取验证码图片
const fetchCaptcha = async () => {
  try {
    keyy.value = Math.random();
    // 把这个格式转换成字符串
    const response = await getCaptcha(keyy.value.toString());
    captchaUrl.value = URL.createObjectURL(response);
    console.log('Captcha URL:', captchaUrl.value); // 调试信息
  } catch (error) {
    console.error('获取验证码图片失败:', error);
  }
};

// 刷新验证码
const refreshCaptcha = () => {
  fetchCaptcha();
};

// 初始化时获取验证码图片
fetchCaptcha();

// 组件卸载时释放 Blob URL
onUnmounted(() => {
  if (captchaUrl.value) {
    URL.revokeObjectURL(captchaUrl.value);
  }
});

const login = async () => {
  loginData.value.key = keyy.value;
  try {
    let result = await userLoginService(loginData.value);

    if (result.msg === "操作成功") {
      // 登录成功处理
      tokenStore.setToken(result.data.token);

      router.push("/");
      ElMessage.success("登录成功");
    } else {
      // 登录失败处理
      fetchCaptcha(); // 刷新验证码
      ElMessage.error(`登录失败: ${result.msg || "未知错误"}`);
    }
  } catch (error) {
    // 捕获网络或其他异常
    console.error('登录请求失败:', error);
    fetchCaptcha(); // 刷新验证码
    ElMessage.error("登录请求失败，请稍后再试");
  }
};
// 处理键盘事件
const handleKeydown = (event) => {
  if (event.key === 'Enter') {
    if (isRegister.value) {
      register();
    } else {
      login();
    }
  }
};
</script>

<template>
  <el-row class="login-page">
    <el-col :span="16" :offset="4" class="form">
      <!-- 注册表单 -->
      <el-form ref="form" size="large" autocomplete="off" v-if="isRegister" :model="registerData" :rules="regrules" @keydown="handleKeydown">
        <el-form-item>
          <h1>注册</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="registerData.password"></el-input>
        </el-form-item>
        <el-form-item prop="repassword">
          <el-input :prefix-icon="Lock" type="password" placeholder="请再次输入密码" v-model="registerData.repassword"></el-input>
        </el-form-item>
        <el-form-item prop="userType">
          <el-radio-group v-model="registerData.userType">
            <el-radio label="admin">管理员</el-radio>
            <el-radio label="teacher">老师</el-radio>
            <el-radio label="student">学生</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="captcha">
          <el-input :prefix-icon="ChatLineRound" style="width:50%" placeholder="请输入验证码" v-model="registerData.captcha"></el-input>
          <img style="width:50%" :src="captchaUrl" width="135px" height="33px" @click="refreshCaptcha" />
        </el-form-item>
        <!-- 注册按钮 -->
        <el-form-item>
          <el-button class="button" type="primary" auto-insert-space @click="register">注册</el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = false;fetchCaptcha();">← 返回</el-link>
        </el-form-item>
      </el-form>
      <!-- 登录表单 -->
      <el-form ref="form" size="large" autocomplete="off" v-else :model="loginData" :rules="logrules" @keydown="handleKeydown">
        <el-form-item>
          <h1>登录</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="loginData.username"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input name="password" :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="loginData.password"></el-input>
        </el-form-item>
        <el-form-item prop="captcha">
          <el-input :prefix-icon="ChatLineRound" style="width:50%" placeholder="请输入验证码" v-model="loginData.captcha"></el-input>
          <img style="width:50%" :src="captchaUrl" width="135px" height="33px" @click="refreshCaptcha" />
        </el-form-item>
        <el-form-item class="flex">
          <div class="flex">
            <el-checkbox>记住我</el-checkbox>
            <el-link type="primary" :underline="false">忘记密码？</el-link>
          </div>
        </el-form-item>
        <!-- 登录按钮 -->
        <el-form-item>
          <el-button class="button" type="primary" auto-insert-space @click="login">登录</el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = true;fetchCaptcha();">注册 →</el-link>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>
<style lang="scss" scoped>
.login-page {
  height: 100vh;
  background: url("@/assets/background.jpeg") no-repeat center / cover;
  background-color: #fff;
  display: flex;
  justify-content: flex-end; /* 将内容向右对齐 */
  align-items: center;

  .form {
    background-color: rgba(255, 255, 255, 0.8); /* 半透明白色背景 */
    backdrop-filter: blur(10px); /* 模糊效果 */
    border-radius: 10px; /* 圆角 */
    padding: 40px;
    width: 100%;
    max-width: 400px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    margin-right: 200px; /* 增加右边距 */
  }
  .button {
      width: 100%;
    }

    .flex {
      width: 100%;
      display: flex;
      justify-content: space-between;
    }
}
</style>        